# -*- coding:utf-8 -*-

__author__ = 'CYY'

import requests
from constant_util import logger, __http_config_file, __user_config_file, Properties

config_http = Properties(__http_config_file).get_properties()

config_user = Properties(__user_config_file).get_properties()


def exec_http(user_id=config_http['http.userid'], mess_txt=config_http['http.mess_text']):
    if user_id.strip() != '' and user_id is not None:
        url = "http://wx.trendy-global.com/WechatsQy/index.php/Api/SendWxMess"

        payload = "user_name=" + config_http['http.username'] + "&password=" + config_http[
            'http.password'] + "&to_userid=" + user_id + "&mess_text=" + mess_txt + "&undefined="
        headers = {
            'Content-Type': "application/x-www-form-urlencoded",
            'Authorization': "Basic ZGxhZG1pbjpUSElOS0JJRw=="
        }

        response = requests.request("POST", url, data=payload.encode(), headers=headers)
        if response.json().get('message') == 'success!':
            logger.info("发送给%s成功！", user_id)
        else:
            logger.warning("发送给%s失败！", user_id)

        # logger.info(response.json().get('message'))
        # logger.info(response.text)


def direct_exec_http(project_name, mess_txt=config_http['http.mess_text']):
    # if config_user[project_name] is not None:
    try:
        user_list = config_user[project_name].split(',')
        if len(user_list) > 1:
            for user_id in user_list:
                exec_http(user_id, mess_txt)
        elif len(user_list) == 1:
            exec_http(config_user[project_name], mess_txt)
        else:
            pass
    except:
        logger.error(project_name + '项目没有配置，请仔细检查user-mapping.config配置！')


def mutiple_exec_http(mess_txt=config_http['http.mess_text']):
    user_list = config_http['http.userid'].split(',')
    if len(user_list) > 1:
        for user_id in user_list:
            exec_http(user_id, mess_txt)
    elif len(user_list) == 1:
        exec_http(mess_txt)
    else:
        pass
